/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import pojo.Danhmuc;
import pojo.Loaimultimedia;
import pojo.Multimedia;
import pojo.Sanpham;
import pojo.Sanphammultimedia;
import pojo.Taikhoan;
import pojo.Tinhtrangsanpham;
import util.HibernateUtil;
import util.UtilCommon;

/**
 *
 * @author WMThiet
 */
public class SanPhamDAO {

    public static int pageCount; // Biến tính số trang, sau mỗi lần tìm kiếm sẽ cập nhật
    public static int listCount; // Biến đếm số sản phẩm

    public static List<Sanpham> LaySPNoiBat() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        List<Sanpham> listSP = null;
        try {
            session.beginTransaction();
            String hql = "from Sanpham sp where sp.daXoa=:dx and sp.danhmuc.laDanhMucTop=:ladmTop ";
            hql += "order by sp.soLuongXem";
            Query query = session.createQuery(hql);
            query.setBoolean("dx", false);
            query.setBoolean("ladmTop", true);
            query.setMaxResults(9);
            listSP = query.list();
        } catch (Exception ex) {
            listSP = null;
        } finally {
            session.close();
        }

        return listSP;
    }

    public static List<Sanpham> LaySPHot() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        List<Sanpham> listSP = null;
        try {
            session.beginTransaction();
            String hql = "from Sanpham sp where sp.daXoa=:daXoa ";
            hql += "order by sp.soLuongdaugia";
            Query query = session.createQuery(hql);
            query.setBoolean("daXoa", false);
            query.setMaxResults(9);
            listSP = query.list();
        } catch (Exception ex) {
            listSP = null;
        } finally {
            session.close();
        }

        return listSP;
    }

    public static List<Sanpham> LaySPTheoDanhMuc(int maDanhMuc) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        List<Sanpham> listSP = null;
        try {
            session.beginTransaction();
            String hql = "from Sanpham sp where sp.daXoa=:dx and sp.danhmuc.maDanhMuc=:maDanhMuc";
            Query query = session.createQuery(hql);
            query.setBoolean("dx", false);
            listSP = query.list();
        } catch (Exception ex) {
            listSP = null;
        } finally {
            session.close();
        }
        return listSP;
    }

    public static List<Sanpham> LaySPTheoDanhMuc(int maDanhMuc, int page, int numberProducts) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        List<Sanpham> listSP = null;
        try {
            session.beginTransaction();
            String hql = "from Sanpham sp where sp.daXoa=:dx and sp.danhmuc.maDanhMuc=:maDanhMuc";
            Query query = session.createQuery(hql);
            query.setInteger("maDanhMuc", maDanhMuc);
            query.setBoolean("dx", false);

            // Tính số trang :
            listSP = query.list();
            pageCount = tinhTrangTheoDSSP(listSP.size(), numberProducts);

            int n = (page - 1) * numberProducts;

            if (numberProducts != -1) {
                query.setFirstResult(n);
                query.setMaxResults(numberProducts);
            }
            listSP = query.list();
        } catch (Exception ex) {
            listSP = null;
        } finally {
            session.close();
        }
        return listSP;
    }

    public static int tinhTrangTheoDSSP(int soLuong, int soLuongSanPhamTrenTrang) {
        int soTrang = 0;

        if (soLuongSanPhamTrenTrang == -1) {
            soTrang = 1;
        } else {
            soTrang = soLuong / soLuongSanPhamTrenTrang;
            if (soLuong % soLuongSanPhamTrenTrang != 0) {
                soTrang++;
            }
        }
        return soTrang;
    }

    public static Sanpham LayChiTietSanPham(int maSP) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Sanpham sanPham = null;
        try {
            session.beginTransaction();
            Sanpham temp = (Sanpham) session.get(Sanpham.class, maSP);

            if (temp.getDaXoa() == false) {
                sanPham = temp;
            }

        } finally {
            session.close();
        }

        return sanPham;
    }

    public static List<Sanpham> LaySPTheoTen(String key, int page, int numberProducts) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        List<Sanpham> listSP = null;
        try {
            session.beginTransaction();
            String hql = "from Sanpham sp where sp.tenSanPham like CONCAT ('%', :tenSP ,'%') and sp.daXoa=:daXoa ";
            hql += "order by sp.soLuongdaugia";
            Query query = session.createQuery(hql);
            query.setString("tenSP", key);
            query.setBoolean("daXoa", false);

            // Tính số trang :
            listSP = query.list();
            pageCount = tinhTrangTheoDSSP(listSP.size(), numberProducts);

            int n = (page - 1) * numberProducts;

            if (numberProducts != -1) {
                query.setFirstResult(n);
                query.setMaxResults(numberProducts);
            }
            listSP = query.list();
        } catch (Exception ex) {
            listSP = null;
        } finally {
            session.close();
        }

        return listSP;
    }

    public static List<Sanpham> LaySPTimKiemNangCao(String tenSP, Danhmuc danhMuc, float giaMin, float giaMax, int page, int numberProducts) {
        if (giaMax == -1) {
            giaMax = Integer.MAX_VALUE;
        }
        Session session = HibernateUtil.getSessionFactory().openSession();
        List<Sanpham> listSP = null;
        try {
            session.beginTransaction();
            String hql = "from Sanpham sp where sp.tenSanPham like CONCAT ('%', :tenSP ,'%') and sp.daXoa=:daXoa and sp.giaHienTai >= :giaMin and sp.giaHienTai <= :giaMax";
            if (danhMuc != null) {
                hql += " and sp.danhmuc = :danhMuc";
            }

            hql += " order by sp.soLuongdaugia";

            Query query = session.createQuery(hql);
            query.setString("tenSP", tenSP);
            query.setBoolean("daXoa", false);
            query.setFloat("giaMin", giaMin);
            query.setFloat("giaMax", giaMax);
            if (danhMuc != null) {
                query.setParameter("danhMuc", danhMuc);
            }

            // Tính số trang :
            listSP = query.list();
            pageCount = tinhTrangTheoDSSP(listSP.size(), numberProducts);

            int n = (page - 1) * numberProducts;

            if (numberProducts != -1) {
                query.setFirstResult(n);
                query.setMaxResults(numberProducts);
            }
            listSP = query.list();
        } catch (Exception ex) {
            listSP = null;
        } finally {
            session.close();
        }

        return listSP;
    }

    public static boolean capNhatSoLanXem(Sanpham sp) {
        boolean result = false;
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            
            Sanpham sanPham = (Sanpham)session.get(Sanpham.class, sp.getMaSanPham());
            sanPham.setSoLuongXem(sp.getSoLuongXem() + 1);
            
            session.update(sanPham);
            transaction.commit();
            result = true;
        } catch (HibernateException ex) {
            transaction.rollback();
            System.err.println(ex);
        } finally {
            session.close();
        }
        return result;
    }
    
    public static List<Sanpham> laySanPhamLienQuan(int masp, Danhmuc danhMuc){
        Session session = HibernateUtil.getSessionFactory().openSession();
        List<Sanpham> listSP = null;
        try {
            session.beginTransaction();
            String hql = "select distinct sp from Sanpham sp where sp.daXoa=:dx and (sp.danhmuc.maDanhMuc=:maDanhMuc or sp.danhmuc.danhmuc.maDanhMuc=:maDMCha) and sp.maSanPham !=:maSP ";
            hql += "order by sp.soLuongdaugia,sp.soLuongXem";
            Query query = session.createQuery(hql);
            query.setInteger("maDanhMuc", danhMuc.getMaDanhMuc());
            query.setInteger("maDMCha", danhMuc.getDanhmuc().getMaDanhMuc());
            query.setBoolean("dx", false);
            query.setInteger("maSP", masp);
            query.setMaxResults(5);
            
            
            listSP = query.list();
            
        } catch (Exception ex) {
            listSP = null;
        } finally {
            session.close();
        }
        return listSP;
    }
    
    public static List<Sanpham> LaySanPhamHetDauGia(){
        Session session = HibernateUtil.getSessionFactory().openSession();
        List<Sanpham> listSP = null;
        try {
            session.beginTransaction();            
                       
            String hql  = "from Sanpham sp where sp.daXoa =0 and sp.daMuaNgay =0 and sp.daXetCT =0 and sp.ngayHetHan <= '" + UtilCommon.DateToString1(new Date()) + "'";
            Query query = session.createQuery(hql);
                                    
            listSP = query.list();            
            
        } catch (Exception ex) {
            listSP = null;
        } finally {
            session.close();
        }
        return listSP;
    }

    public static List<Sanpham> LaySanPhamDaDang(Taikhoan tk, int page) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        List<Sanpham> listSP = null;
        try {
            session.beginTransaction();
            String hql = "from Sanpham sp where sp.taikhoan=:tk and sp.daXoa=:daXoa ";
            hql += "order by sp.ngayDang desc";
            Query query = session.createQuery(hql);
            query.setParameter("tk", tk);
            query.setBoolean("daXoa", false);

            int numberProducts = 6;
            // Tính số trang :
            listSP = query.list();
            pageCount = tinhTrangTheoDSSP(listSP.size(), numberProducts);
            listCount = listSP.size();

            int n = (page - 1) * numberProducts;

            if (numberProducts != -1) {
                query.setFirstResult(n);
                query.setMaxResults(numberProducts);
            }
            listSP = query.list();
        } catch (Exception ex) {
            listSP = null;
        } finally {
            session.close();
        }

        return listSP;
    }
    
    public static List<Sanpham> TimSanPhamDaDang(String key, Taikhoan tk, int page) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        List<Sanpham> listSP = null;
        try {
            session.beginTransaction();
            String hql = "from Sanpham sp where sp.tenSanPham like CONCAT ('%', :tenSP ,'%') and sp.taikhoan=:tk and sp.daXoa=:daXoa ";
            hql += "order by sp.ngayDang desc";
            Query query = session.createQuery(hql);
            query.setString("tenSP", key);
            query.setParameter("tk", tk);
            query.setBoolean("daXoa", false);

            int numberProducts = 6;
            // Tính số trang :
            listSP = query.list();
            pageCount = tinhTrangTheoDSSP(listSP.size(), numberProducts);
            listCount = listSP.size();

            int n = (page - 1) * numberProducts;

            if (numberProducts != -1) {
                query.setFirstResult(n);
                query.setMaxResults(numberProducts);
            }
            listSP = query.list();
        } catch (Exception ex) {
            listSP = null;
        } finally {
            session.close();
        }

        return listSP;
    }
    
    public static boolean CapNhatXoaSanPham(int maSP) {
        boolean result = false;
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            
            Sanpham sanPham = (Sanpham)session.get(Sanpham.class, maSP);
            sanPham.setDaXoa(true);
            
            session.update(sanPham);
            transaction.commit();
            result = true;
        } catch (HibernateException ex) {
            transaction.rollback();
            System.err.println(ex);
        } finally {
            session.close();
        }
        return result;
    }


    public static int ThemMoi(Integer maTaiKhoan, String namePro, int maDM, long giaKhoiDiem, long giaMuaNgay, Date dateEnd, String paymentInfo, String detailInfo, int tinhTrang) {
        int result = 0;
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            
            Taikhoan tk = (Taikhoan)session.get(Taikhoan.class, maTaiKhoan);
            Danhmuc dm = (Danhmuc)session.get(Danhmuc.class, maDM);
            Tinhtrangsanpham tt = (Tinhtrangsanpham)session.get(Tinhtrangsanpham.class, tinhTrang);
            
            Sanpham sp = new Sanpham();
            sp.setTaikhoan(tk);
            sp.setDanhmuc(dm);
            sp.setTinhtrangsanpham(tt);
            sp.setDaMuaNgay(false);
            sp.setDaXetCT(false);
            sp.setDaXoa(false);
            sp.setHinhMoTa("images/noimage.jpg");
            sp.setGiaHienTai(giaKhoiDiem);
            sp.setGiaKhoiDiem(giaKhoiDiem);
            sp.setGiaMuaNgay(giaMuaNgay);
            sp.setMoTaSanPham(detailInfo);
            sp.setNgayDang(new Date());
            sp.setNgayHetHan(dateEnd);
            sp.setSoLuongXem(0);
            sp.setSoLuongdaugia(0);
            sp.setTenSanPham(namePro);
            sp.setThongTinThanhToan(paymentInfo);
            
            session.save(sp);
            transaction.commit();
            result = sp.getMaSanPham();
            
        } catch (HibernateException ex) {
            transaction.rollback();
            result = 0;
        } finally {
            session.close();
        }
        return result;
    }
    
    public static boolean UpdateMultimedia(int masp,List<String> listFile,String mainFile){
        boolean bDone = false;
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        
        try{            
            transaction = session.beginTransaction();
            
            Sanpham sp = (Sanpham)session.get(Sanpham.class, masp);
            sp.setHinhMoTa("images/data/product/" + mainFile); 
            session.update(sp);
            
            Loaimultimedia lm = (Loaimultimedia)session.get(Loaimultimedia.class, 1);
            listFile.remove(mainFile);
            
            for (String img : listFile) {
                Sanphammultimedia spm = new Sanphammultimedia();
                
                Multimedia m = new Multimedia();
                m.setDungLuong((float)1.0);
                m.setKichThuoc((float)1.0);
                m.setLinkUrl("images/data/product/" + img);
                m.setLoaimultimedia(lm);
                m.setTenMt(img);
                
                spm.setSanpham(sp);
                spm.setMultimedia(m);
                
                session.save(spm);
            }
            
            transaction.commit();
            
            bDone = true;
            
        }catch(Exception ex){            
            transaction.rollback();
            bDone = false;
            
        }finally{
            session.close();
        }
        
        return bDone;
    }
    
    public static int LayTongSanPham(){
        Session session = HibernateUtil.getSessionFactory().openSession();
        int tong = 0;

        try {
            session.beginTransaction();            
                       
            String hql  = "from Sanpham sp where sp.daXoa =0";
            Query query = session.createQuery(hql);
                                    
            tong = query.list().size();            
            
        } catch (Exception ex) {
            tong = 0;
        } finally {
            session.close();
        }
        return tong;
    }
}
